package com.tsyz.servlet.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

// 启用配置绑定
@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolConfig {

    // 注入配置属性（对应application.yml中的thread-pool）
    private final ThreadPoolProperties properties;

    // 构造器注入配置
    public ThreadPoolConfig(ThreadPoolProperties properties) {
        this.properties = properties;
    }

    // 1. 定义查询线程池
    @Bean("queryThreadPool")
    public ThreadPoolTaskExecutor queryThreadPool() {
        return createThreadPool(properties.getQuery());
    }

    // 2. 定义提交合规任务线程池（对应用户示例）
    @Bean("submitComplianceTaskPool")
    public ThreadPoolTaskExecutor submitComplianceTaskPool() {
        return createThreadPool(properties.getSubmitCompliance());
    }

    // 通用线程池创建方法（复用逻辑）
    private ThreadPoolTaskExecutor createThreadPool(ThreadPoolProperties.PoolConfig config) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心参数配置
        executor.setCorePoolSize(config.getCorePoolSize());
        executor.setMaxPoolSize(config.getMaxPoolSize());
        executor.setQueueCapacity(config.getQueueCapacity());
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        executor.setThreadNamePrefix(config.getThreadNamePrefix());

        // 拒绝策略（根据配置字符串转换）
        executor.setRejectedExecutionHandler(resolveRejectedPolicy(config.getRejectedPolicy()));

        // 初始化线程池（必须调用，否则线程池不生效）
        executor.initialize();
        return executor;
    }

    // 解析拒绝策略（字符串转ThreadPoolExecutor的策略）
    private RejectedExecutionHandler resolveRejectedPolicy(String policy) {
        // 根据输入的策略名称，返回对应的 ThreadPoolExecutor.RejectedExecutionHandler 实例
        switch (policy) {
            case "ABORT":
                // 如果策略是 "ABORT"，返回一个 AbortPolicy 实例
                // AbortPolicy 会在任务被拒绝时抛出 RejectedExecutionException
                return new ThreadPoolExecutor.AbortPolicy();

            case "DISCARD":
                // 如果策略是 "DISCARD"，返回一个 DiscardPolicy 实例
                // DiscardPolicy 会在任务被拒绝时直接丢弃任务，不做任何处理
                return new ThreadPoolExecutor.DiscardPolicy();

            case "DISCARD_OLDEST":
                // 如果策略是 "DISCARD_OLDEST"，返回一个 DiscardOldestPolicy 实例
                // DiscardOldestPolicy 会丢弃队列中最旧的任务，然后尝试重新提交被拒绝的任务
                return new ThreadPoolExecutor.DiscardOldestPolicy();

            case "CALLER_RUNS":
                // 如果策略是 "CALLER_RUNS"，返回一个 CallerRunsPolicy 实例
                // CallerRunsPolicy 会在调用者线程中直接运行被拒绝的任务
                return new ThreadPoolExecutor.CallerRunsPolicy();

            default:
                // 如果输入的策略名称不匹配任何已知策略，抛出 IllegalArgumentException
                // 提示不支持的拒绝策略
                throw new IllegalArgumentException("不支持的拒绝策略：" + policy);
        }
    }
}